/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

#include "include/paddr.h"
#include "include/common.h"
#include "stdio.h"

static uint8_t *pmem = NULL;


uint8_t* guest_to_host(paddr_t paddr) { return pmem + paddr - MEM_START; }
paddr_t host_to_guest(uint8_t *haddr) { return haddr - pmem + MEM_START; }

word_t pmem_read(paddr_t addr, int len) {
  word_t ret = host_read(guest_to_host(addr), len);
  return ret;
}

void pmem_write(paddr_t addr, int len, word_t data) {
  host_write(guest_to_host(addr), len, data);
}

void out_of_bound(paddr_t addr) {
  printf("[memory] address = 0x%x is out of bound of pmem@[0x%x,0x%x]\n", addr, MEM_START, MEM_END);
  assert(0);
}

void init_mem() {
  printf("Initializing Memory\n");
  pmem = (uint8_t *)malloc(MEM_END - MEM_START + 1);
  //Log("physical memory area [" FMT_PADDR ", " FMT_PADDR "]", PMEM_LEFT, PMEM_RIGHT);
}

// word_t paddr_read(paddr_t addr, int len) {

//   #ifdef CONFIG_MTRACE
//     printf("Read addr: 0x%x, Len: %d \n",addr,len);
//   #endif

//   if (likely(in_pmem(addr))) return pmem_read(addr, len);
//   out_of_bound(addr); 
//   return 0;
// }

// void paddr_write(paddr_t addr, int len, word_t data) {

//   #ifdef CONFIG_MTRACE
//     printf("Write addr: 0x%x, Len: %d, Data:%x \n",addr,len,data);
//   #endif

//   if (likely(in_pmem(addr))) { pmem_write(addr, len, data); return; }
//   out_of_bound(addr);
// }
